import { reactive, readonly } from 'vue';

let modules = [];
// 加载modules下所有路由文件
let modelsFile = import.meta.glob('./modules/*.js'),
  modelsArr = Object.values(modelsFile);
for (let modelsIndex in modelsArr) {
  var file_name = modelsArr[modelsIndex].name.replace(
    /(.*\/)*([^.]+).*/gi,
    '$2'
  );
  let modelsItem = await modelsArr[modelsIndex]();
  modelsItem.default.localArr.forEach((element) => {
    console.log(window.$core.getLocal(element));
    if (window.$core.getLocal(element) !== 'undefined') {
      modelsItem.default.stateObj[element] = window.$core.getLocal(element);
    }
  });
  modelsItem.default.file_name = file_name;
  modules.push(modelsItem.default);
}

let install = (Vue) => {
  let store = {};
  modules.forEach((element) => {
    let modulesItem = {};
    modulesItem.stateReactive = reactive(element.stateObj);
    modulesItem.state = readonly(modulesItem.stateReactive);
    modulesItem.setState = (key, value) => {
      if (element.localArr.includes(key)) {
        window.$core.setLocal(key, value);
      }
      modulesItem.stateReactive[key] = value;
    };
    store[element.file_name] = modulesItem;
    Vue.config.globalProperties['$store_' + element.file_name] = modulesItem;
    Vue.provide('$store_' + element.file_name, modulesItem);
  });
};

export default {
  install,
};
